//
//  HZJTabbar.swift
//  HZJTab
//
//  Created by HZJ on 2017/4/7.
//  Copyright © 2017年 HZJ. All rights reserved.
//

import UIKit
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}

// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l > r
  default:
    return rhs < lhs
  }
}

enum HZJError:Error {
    /**
    自定义异常
    */
    case errorOne
}
class HZJTabbar: UIView {
    weak var delegate:HZJTabbarDelegate?
    var btnArray:[HZJTabBarButton] = []
    //默认选择的按钮
    var selectedIndex = 0 {
        didSet{
            //设置第一个按钮为默认点击状态
            lastSelectedBtn!.isSelected = false
            for btn in self.btnArray {
                if btn.index == selectedIndex {
                    lastSelectedBtn = btn

                }
            }
//            lastSelectedBtn = btnArray[selectedIndex]
            lastSelectedBtn!.isSelected = true
        }
    }
    //MARK: 主要方法（必须实现）
    /**生成tab按钮
     VCcount            - 控制器的数目
     titleArray         - 控制器的名称 在语言国际化时的key，有顺序，可传空
     imgStrs            - 控制器按钮的图片名集合，有顺序，可传空
     selectedImageStrs  - 控制器按钮高亮时的图片名集合，有顺序，可传空
     */
    func tabBarWith(_ VCcount:Int,titleArray:[String]?,imgStrs:[String]?,selectedImageStrs:[String]?){
        
        if titleArray?.count > VCcount || imgStrs?.count > VCcount {
            print("创建HZJTabbar时传入的名称或图像名称数目大于控制器数目")
        }
        
        //先清空
        for btn in btnArray {
            btn.removeFromSuperview()
        }
        btnArray = []
        
        //先创建按钮
        for i in 0..<VCcount {
            let btn = HZJTabBarButton(frame: CGRect())
            btn.index = i
            btn.addTarget(self, action: #selector(HZJTabbar.clickTheBtn(_:)), for: UIControlEvents.touchUpInside)
            self.addSubview(btn)
            self.btnArray.append(btn)
        }
        //按钮赋值标题(设置btn的theTitle属性就行)
        if titleArray != nil {
            for i in 0..<titleArray!.count {
                btnArray[i].theTitle = titleArray![i]
            }
        }
        //按钮设置normal图片
        if imgStrs != nil {
            let count = imgStrs!.count < VCcount ? imgStrs!.count : VCcount
            for i in 0..<count {
                if let image = UIImage(named: imgStrs![i]) {
                    btnArray[i].setImage(image, for: UIControlState())

                }
            }
        }
        //按钮设置Selected图片
        if selectedImageStrs != nil {
            let count = selectedImageStrs!.count < VCcount ? selectedImageStrs!.count : VCcount
            for i in 0..<count {
                if let image = UIImage(named: selectedImageStrs![i]) {
                    btnArray[i].setImage(image, for: UIControlState.selected)
                    
                }
            }
        }
        
        //设置第一个按钮为默认点击状态
        lastSelectedBtn = btnArray[self.selectedIndex]
        lastSelectedBtn!.isSelected = true
    }
    //MARK: 创建无点击效果的按钮
    /**插入“没有被选择”效果的按钮（HZJTabBarButton）
     * btnTitleKey  - 按钮的文字在语言国际化时的key
     * btnImageName - 按钮上的图片的名称
     * btnIndex     - 按钮的序号，必须需小于0
     * atIndex      - 插入按钮的位置
     */
    func insertNoSelectedBtn(_ btnTitleKey:String?,btnImageName:String?,btnIndex:Int,atIndex:Int,isNormalBtn:Bool){
        guard btnIndex < 0 && atIndex >= 0 && atIndex < self.btnArray.count else {
            return
        }
        
        let btn = HZJTabBarButton()
        btn.isNormal = isNormalBtn
        btn.setImage(UIImage(), for: UIControlState())
        if btnTitleKey != nil {
            btn.theTitle = btnTitleKey!
        }
        if btnImageName != nil {
            if let image = UIImage(named: btnImageName!) {
                btn.setImage(image, for: UIControlState())
            }
        }
        btn.index = btnIndex
        btn.addTarget(self, action: #selector(HZJTabbar.clickTheBtn(_:)), for: UIControlEvents.touchUpInside)
        self.addSubview(btn)
        btnArray.insert(btn, at: atIndex)
    }
    
    //MARK: 刷新功能
    /**
     刷新tab上的所有按钮上的文字
     */
    func reloadTheAllTabBarBtn(){
        for i in 0...self.btnArray.count {
            self.reloadTheTabBarBtn(i)
        }
    }
    /**
     刷新tab上的某个按钮上的文字(index 为0，1，2，3。。。）
     */
    func reloadTheTabBarBtn(_ index:NSInteger){
        guard index < self.btnArray.count else{
            return
        }
        self.btnArray[index].reloadTheTitle()
    }
    //MARK: 按钮点击事件
    /**
    记录上次点击的按钮
    */
    fileprivate var lastSelectedBtn:HZJTabBarButton!
    
    @objc func clickTheBtn(_ btn:HZJTabBarButton){
        guard lastSelectedBtn != btn else {
            return
        }
        if btn.index >= 0 {
            lastSelectedBtn.isSelected = false
            lastSelectedBtn = btn
            btn.isSelected = true
        }
        self.delegate?.clickTheTarBarButton(btn)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        for i in 0..<btnArray.count {
            btnArray[i].frame = CGRect(x: self.frame.width / CGFloat(btnArray.count) * CGFloat(i),y: 0,width: self.frame.width / CGFloat(btnArray.count),height: self.frame.height)
        }
    }
}
//MARK: 代理（若不加@obj，则无法在oc中调用）
@objc protocol HZJTabbarDelegate:NSObjectProtocol {
    func clickTheTarBarButton(_ btn:HZJTabBarButton)
}

